from locust import HttpUser, task, between
import random
import string

class BookApiUser(HttpUser):
    wait_time = between(1, 3)  # 用户等待时间1-3秒
    
    # 生成随机字符串
    def random_string(self, length=10):
        return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
    
    @task(3)  # 权重3，更频繁执行
    def get_books(self):
        # 测试分页获取书籍列表
        page = random.randint(0, 10)
        size = random.randint(5, 20)
        self.client.get(f"/api/books?page={page}&size={size}")
    
    @task(2)
    def search_books(self):
        # 测试搜索书籍
        keyword = self.random_string(random.randint(1, 5))
        self.client.get(f"/api/books/search?name={keyword}")
    
    @task(1)
    def get_book_detail(self):
        # 测试获取书籍详情
        book_id = random.randint(1, 1000)  # 假设ID范围1-1000
        self.client.get(f"/api/books/{book_id}")
    
    @task(1)
    def create_book(self):
        # 测试创建书籍
        headers = {"Content-Type": "application/json"}
        data = {
            "name": f"Book_{self.random_string(5)}",
            "author": f"Author_{self.random_string(4)}",
            "isbn": str(random.randint(1000000000, 9999999999)),
            "typeId": random.randint(1, 10)
        }
        self.client.post("/api/books", json=data, headers=headers)